package me.ratel.demo.eBook.interfaces.web;

import me.ratel.demo.eBook.application.IUserService;
import me.ratel.demo.eBook.infrastructure.exceptions.BusinessException;
import me.ratel.demo.eBook.interfaces.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ${user}
 * @time 2016/6/13 8:13
 */
@Controller
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired private IUserService userService;

    @RequestMapping("user/oauth2/authorize") public void authorizeOAuth2User(HttpServletRequest request, HttpServletResponse response) {
        WebError webError;
        try {
            String state = request.getParameter("state");

            String code = request.getParameter("code");

            logger.info("/user/oauth2/authorize 参数 [{}] [{}]", state, code);

            userService.authorizeOAuth2User(code, state);

            webError = new WebError(WebConstants.ErrorHeader.SUCCESS, null);
        } catch (BusinessException bize) {
            logger.info("/user/oauth2/authorize 业务异常", bize);
            webError = new WebError(bize.getIError());
        } catch (Throwable t) {
            logger.info("/user/oauth2/authorize 系统异常", t);
            webError = new WebError(WebConstants.ErrorHeader.SYS_ERROR, null);
        }
        ResponseUtil.writeJSON(response, webError);
    }
}
